package ddz.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Zlib {

    public static byte[] compress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return bytes;
        }
        Deflater compresser = new Deflater();
        compresser.reset();
        compresser.setInput(bytes);
        compresser.finish();
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length)) {
            byte[] buf = new byte[1024];
            while (!compresser.finished()) {
                int i = compresser.deflate(buf);
                bos.write(buf, 0, i);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            compresser.end();
        }
        return bytes;
    }

    /**
     * 使用gzip进行解压缩
     */
    public static byte[] decompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return bytes;
        }
        Inflater decompresser = new Inflater();
        decompresser.reset();
        decompresser.setInput(bytes);
        try (ByteArrayOutputStream o = new ByteArrayOutputStream(bytes.length)) {
            byte[] buf = new byte[1024];
            while (!decompresser.finished()) {
                int i = decompresser.inflate(buf);
                o.write(buf, 0, i);
            }
            return o.toByteArray();
        } catch (IOException | DataFormatException e) {
            e.printStackTrace();
        } finally {
            decompresser.end();
        }
        return bytes;
    }

}
